<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件</title>
  </head>
  <body>
    <button id="btn1">事件一</button>
    <button id="btn2">事件二</button>
    <button id="btn3">移除事件二</button>
    <button id="btn4">恢复事件二</button>
  </body>
  <script>
    const btn1 = document.getElementById("btn1");
    const btn2 = document.getElementById("btn2");
    const btn3 = document.getElementById("btn3");
    const btn4 = document.getElementById("btn4");
    main();
    function main() {
      // 方式一（兼容性好）
      btn1.onclick = changeBgColor;
      btn3.onclick = removeEvent;
      btn4.onclick = setEventListener;

      // 方式二（不支持IE9、功能更强大）
      btn2.addEventListener("click", changeBgColor);
    }
    function random(number) {
      return Math.floor(Math.random() * (number + 1));
    }

    //监听btn Click事件
    function setEventListener() {
      btn2.addEventListener("click", changeBgColor);
    }

    // 创建事件处理函数
    function changeBgColor() {
      let rndCol =
        "rgb(" + random(255) + "," + random(255) + "," + random(255) + ")";
      document.body.style.backgroundColor = rndCol;
    }

    // 移除事件
    function removeEvent() {
      btn2.removeEventListener("click", changeBgColor);
    }
  </script>
</html>
